#_*_ coding: utf-8 _*_
import requests
import json
import os
import time
import logging
from datetime import datetime
from utils import synergism, zytoken,zymysql,userface


# 配置参数
RETRY_TIMES = 3  # 最大重试次数
DELAY_SECONDS = 7  # 默认延迟时间（秒）
Port = 4370


# 设置日志配置
current_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.join(os.path.dirname(current_dir), "logs")  # 子目录名称
log_filename = os.path.join(target_dir, "attendance_record.log")
logging.basicConfig(
    level=logging.INFO,  # 设置日志级别为INFO
    format='%(asctime)s - %(levelname)s - %(message)s',  # 设置日志格式
    handlers=[
        logging.FileHandler(log_filename),  # 将日志写入文件
        logging.StreamHandler()  # 也打印到控制台
    ]
)


# 获取表单信息
def StitchData(summaryid):
    url = 'http://192.168.0.13:4865/seeyon/rest/form/getformdata/' + str(summaryid)
    ZYtoken = zytoken.getzytoken()
    header = {"token": ZYtoken}
    try:
        req = requests.get(url, headers=header)
        result = req.json()  # 获得致远表单数据
        zhu = json.loads(result['DataJson'])[0]  # 主表字段
        print(zhu)
        devlistz = ['192.168.4.2:1', '192.168.0.51:1', '192.168.0.52:2', '192.168.0.53:3', '192.168.0.54:4', '192.168.0.55:5', '192.168.0.56:6', '192.168.0.57:7']

        logging.info(f"成功获取表单数据: {zhu}---{devlistz}")
        return zhu, devlistz

    except Exception as e:
        logging.error(f"获取表单数据失败, summaryid: {summaryid}, 错误: {str(e)}")
        raise  # 重新抛出异常，以便在外层捕获并记录


def perform_operation(operation, operation_name, **kwargs):
    """执行操作并自动重试"""
    for attempt in range(1, RETRY_TIMES + 1):
        try:
            if operation(**kwargs):
                return
            print(f"{operation_name}失败，尝试 {attempt}/{RETRY_TIMES}")
        except Exception as e:
            print(f"{operation_name}异常: {str(e)}，尝试 {attempt}/{RETRY_TIMES}")

        if attempt < RETRY_TIMES:
            time.sleep(DELAY_SECONDS)
    raise


def process_device(ip, machine_num, enroll_num, dwBackupNumber):
    """处理单个设备"""
    try:
        # 连接设备
        perform_operation(
            userface.connect_to_device, "连接设备",ip=ip, port=Port
        )

        # 创建用户
        perform_operation(
            userface.delete_user, "删除用户",
            dwMachineNumber=machine_num, dwEnrollNumber= enroll_num, dwBackupNumber= dwBackupNumber
        )

        print("所有操作成功完成")

    except Exception as e:
        print(f"操作失败: {str(e)}")
        raise


def devicemain(zhu, devlistz):
    enroll_num = zhu['field0160']   # 考勤号码
    dwBackupNumber = 12
    for entry in devlistz:
        try:
            ip, machine_num = entry.split(':')
            print(f"====== 处理设备 {ip} (机器号:{machine_num}) ======")
            process_device(ip, machine_num, enroll_num, dwBackupNumber)

        except Exception as e:
            print(f"设备操作最终失败: {str(e)}")
        finally:
            time.sleep(DELAY_SECONDS)  # 设备间间隔


def insertusersql(zhu):
    enroll_num = zhu['field0160']  # 考勤号码
    # 先查询用户是否已存在
    check_sql = "SELECT COUNT(*) FROM userinfo WHERE Badgenumber = %s"
    try:
        # 执行查询
        existing_count = zymysql.zkteco_query(check_sql, (enroll_num,))[0][0]
        if existing_count > 0:
            delete_sql = "DELETE FROM userinfo WHERE Badgenumber = %s"
            delete_count = zymysql.zkteco_delete(delete_sql, (enroll_num,))[0][0]
            print(f"成功删除{delete_count} 数据记录")
            return True  # 或者根据业务需求返回False
        else:
            print(f"用户考勤号 {enroll_num} 不存在，跳过删除")
            return True

    except Exception as e:
        print(f"操作出错: {e}")
        return False


def start(summaryid):
    try:
        zhu, devlistz = StitchData(summaryid)
    except Exception as e:
        logging.error(f"获取表单数据失败, summaryid: {summaryid}, 错误: {str(e)}")
        # synergism.start(summaryid, False, "数据提取不成功:" + str(e))
        return  # 终止进一步操作

    # 考勤设备推送处理
    try:
        devicemain(zhu, devlistz)
    except Exception as e:
        logging.error(f"推送创建失败, summaryid: {summaryid}, 错误: {str(e)}")
        # synergism.start(summaryid, False, f"推送创建失败, 请重新提交审批: {str(e)}")
        return  # 终止进一步操作

    # 更新考勤数据库
    try:
        insertsum = insertusersql(zhu)
        if insertsum:
            # synergism.start(summaryid, True, "同意")
            logging.info(f"更新处理完成，summaryid: {summaryid}")
        else:
            logging.error(f"更新创建失败, summaryid: {summaryid}")
            # synergism.start(summaryid, False, f"更新数据库失败, 请重新提交审批!")
    except Exception as e:
        logging.error(f"更新创建失败, summaryid: {summaryid}, 错误: {str(e)}")
        # synergism.start(summaryid, False, f"更新数据库失败, 请重新提交审批: {str(e)}")


if __name__ == '__main__':

    summaryid = "-8705326366004655219"
    start(summaryid)
